<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑角色' : '新增角色'"
    width="600px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
      label-position="right"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入角色名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="角色编码" prop="code">
        <el-input
          v-model="formData.code"
          placeholder="请输入角色编码（英文字母、数字、下划线）"
          maxlength="30"
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入角色描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: Boolean,
  role: Object
})

const emit = defineEmits(['update:visible', 'confirm'])

const formRef = ref()
const submitLoading = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.role?.id)

const formData = reactive({
  name: '',
  code: '',
  description: '',
  status: 1
})

const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { 
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, 
      message: '角色编码只能包含字母、数字和下划线，且以字母开头', 
      trigger: 'blur' 
    },
    { min: 2, max: 30, message: '角色编码长度在 2 到 30 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 监听role变化，初始化表单数据
watch(() => props.role, (newRole) => {
  if (newRole) {
    Object.assign(formData, {
      name: newRole.roleName || newRole.name || '',
      code: newRole.roleCode || newRole.code || '',
      description: newRole.description || '',
      status: newRole.status ?? 1
    })
  }
}, { immediate: true })

// 监听对话框显示，重置表单
watch(() => props.visible, (visible) => {
  if (visible && !props.role) {
    resetForm()
  }
})

const resetForm = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    description: '',
    status: 1
  })
  formRef.value?.clearValidate()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const submitData = { ...formData }
    
    // 如果角色编码为空，则自动生成
    if (!submitData.code || submitData.code.trim() === '') {
      submitData.code = generateRoleCode(submitData.name)
    }
    
    emit('confirm', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 自动生成角色编码
const generateRoleCode = (roleName) => {
  if (!roleName) return ''
  
  // 将中文和特殊字符转换为拼音或英文
  const codeMap = {
    '管理员': 'admin',
    '用户': 'user',
    '操作员': 'operator',
    '审核员': 'auditor',
    '测试': 'test',
    '开发': 'developer',
    '运维': 'ops',
    '客服': 'service',
    '销售': 'sales',
    '财务': 'finance'
  }
  
  // 先尝试从映射表获取
  if (codeMap[roleName]) {
    return codeMap[roleName]
  }
  
  // 如果是英文，转换为小写并添加时间戳避免重复
  const englishMatch = roleName.match(/[a-zA-Z]+/)
  if (englishMatch) {
    const base = englishMatch[0].toLowerCase()
    const timestamp = Date.now().toString().slice(-4)
    return `${base}_${timestamp}`
  }
  
  // 默认生成
  const timestamp = Date.now().toString().slice(-6)
  return `role_${timestamp}`
}

const handleCancel = () => {
  dialogVisible.value = false
}

const handleClosed = () => {
  resetForm()
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__body) {
  padding: 20px 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.form-item-tip {
  font-size: 12px;
  color: #8c8c8c;
  margin-top: 4px;
  line-height: 1.2;
}
</style>
